#include "xmlutils.h"

ElementList::ElementList() {}

ElementList::ElementList( TiXmlHandle const & handle )
{
    TiXmlElement * brother = handle.ToElement();
    for( ; brother; brother = brother->NextSiblingElement() )
    {
        m_elements.push_back( TiXmlHandle( brother ) );
    }
}

TiXmlDocument * XmlOperator::loadXml( const char * fileName )
{
    TiXmlDocument * doc = new TiXmlDocument( fileName );
    if( doc->LoadFile() )
        return doc;
    return NULL;
}

ElementList XmlOperator::getChildElements( const TiXmlDocument * doc )
{
    if( doc->NoChildren() )
        return ElementList();
    else
        return ElementList( TiXmlHandle(
            const_cast< TiXmlElement* >( doc->FirstChildElement() ) ) );
}

ElementList XmlOperator::getChildElements( TiXmlHandle const & elem )
{
    if( elem.ToElement()->NoChildren() )
        return ElementList();
    else
        return ElementList( TiXmlHandle( elem.FirstChildElement().ToElement() ) );
}

TiXmlHandle XmlOperator::getFirstElement( const TiXmlDocument * doc )
{
    TiXmlHandle handle( const_cast<TiXmlDocument*>(doc) );
    return handle.FirstChildElement();
}

TiXmlHandle XmlOperator::getChildElement( const TiXmlDocument * doc,
                                          std::string const & tagName,
                                          int index )
{
    TiXmlHandle handle( const_cast<TiXmlDocument*>(doc) );
    return handle.ChildElement( tagName.c_str(), index );
}

TiXmlHandle XmlOperator::getChildElement( TiXmlHandle const & elem,
                                          std::string const & tagName,
                                          int index )
{
    return elem.ChildElement( tagName.c_str(), index );
}

std::string XmlOperator::getElementTag( TiXmlHandle const & elem )
{
    return elem.ToElement()->Value();
}

std::string XmlOperator::getAttribute( TiXmlHandle const & elem,
                                       std::string const & name )
{
    const char * attr = elem.ToElement()->Attribute( name.c_str() );
    if( NULL != attr )
        return attr;
    return std::string();
}

std::string XmlOperator::getText( TiXmlHandle const & elem )
{
    const char * text = elem.ToElement()->GetText();
    if( NULL != text )
        return text;
    return std::string();
}

bool XmlOperator::haveChildElems( TiXmlHandle const & elem )
{
    return !( elem.ToElement()->NoChildren() );
}

bool XmlOperator::isNullHandle( TiXmlHandle const & elem )
{
    return ( NULL == elem.ToNode() ) ? true : false;
}

